package com.lcicl.reggie.controller;
/*
  Date: 2023/09/13
  Author: Luochao
  Description:
        套餐

*/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcicl.reggie.common.R;
import com.lcicl.reggie.entity.*;
import com.lcicl.reggie.entity.dto.DishDto;
import com.lcicl.reggie.entity.dto.SetmealDto;
import com.lcicl.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealCotroller {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;



    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();     //查询套餐
        queryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, queryWrapper);

        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");     //将套餐包装成DTO
        List<Setmeal> records = setmealPage.getRecords();
        System.out.println(records);

        List<SetmealDto> recordsLst = records.stream().map(setmeal -> {     //将Page<Setmeal>里的List<Setmeal> records
            SetmealDto setmealDto = new SetmealDto();                       //转换为Page<SetmealDto>里的List<SetmealDto> recordsLst
            BeanUtils.copyProperties(setmeal, setmealDto);

            Long categoryId = setmeal.getCategoryId();
            Category category = categoryService.getById(categoryId);
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(recordsLst);

        return R.success(setmealDtoPage);
    }


    /**
     * 添加套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping()
    @CacheEvict(value = "setmealCache",allEntries = true)//删除 setmealCache 下所有的缓存
    public R<String> post(@RequestBody SetmealDto setmealDto) {
        setmealService.saveSetmealDto(setmealDto);
        return R.success("添加成功");
    }

    /**
     * 启用&禁用
     *
     * @param status
     * @param longs
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)//删除 setmealCache 下所有的缓存
    public R<String> status(@PathVariable(value = "status") Integer status,
                            @RequestParam(name = "ids", required = true) ArrayList<Long> longs) {
        longs.stream().forEach((item) -> {
            LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Setmeal::getId, item).set(Setmeal::getStatus, status);
            setmealService.update(updateWrapper);
        });
        return R.success("修改成功");
    }

    /**
     * 套餐数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getUpdate(@PathVariable(value = "id") Long id) {

        SetmealDto setmealDto = setmealService.getSetmealDto(id);

        return R.success(setmealDto);
    }

    /**
     * 更新套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping()
    @CacheEvict(value = "setmealCache",allEntries = true)//删除 setmealCache 下所有的缓存
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateSetmealDto(setmealDto);
        return R.success("更新成功");
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping()
    @CacheEvict(value = "setmealCache",allEntries = true)//删除 setmealCache 下所有的缓存
    public R<String> delete(@RequestParam(name = "ids") ArrayList<Long> ids) {
        for (Long id : ids) {       //若在售则不能删除
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal.getStatus() == 1) {
                return R.error("起售状态不能删除");
            }
        }
        setmealService.deleteSetmeals(ids);
        return R.success("删除成功");
    }

    /**
     * 展示套餐详情
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+':'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //查出该套餐分类的所有套餐
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> setmeals = setmealService.list(setmealQueryWrapper);

        return R.success(setmeals);
    }

    /**
     * 展示单个套餐
     * @param setmealId
     * @return
     */
    @GetMapping("dish/{id}")
    public R<List<DishDto>> list(@PathVariable(value = "id") Long setmealId) {


        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);

        List<DishDto> collect = setmealDishes.stream().map(setmealDish -> {     //遍历套餐里面的菜品

            DishDto dishDto = new DishDto();
            dishDto.setCopies(setmealDish.getCopies());//每个菜品份数


            Long dishId = setmealDish.getDishId();


            Dish dish = dishService.getById(dishId);  //查每个菜的信息
            BeanUtils.copyProperties(dish, dishDto); //拷贝每个菜品的信息

            //查菜品口味
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(flavors);

            return dishDto;
        }).collect(Collectors.toList());


        return R.success(collect);
    }

}
